package com.yumeng.common.helper;

import java.text.DecimalFormat;

/**
 * @author wxd
 * @date 2022/10/8 9:49
 */
public class DoubleHelper {

    /**
     * 四舍五入
     * @param dVal
     * @return
     */
    public static Double getRound(Double dVal) {
        return (double) Math.round(dVal * 100) / 100;
    }

    public static Double parseDouble(String strVal){
        if (strVal == null){
            return null;
        }
        try {
            return Double.parseDouble(strVal);
        }catch (NumberFormatException e){
            return null;
        }
    }

    /**
     * 转化成百分比(包含百分号)
     * 2位小数
     * @param num
     * @return
     */
    public static String percentStrWithFlag(Double num) {
        if (num != null) {
            if (num >= 0) {
                return String.format("%.2f", num*100) + "%";
            }else {
                return "-%";
            }
        }else {
            return "--%";
        }
    }

    /**
     * 转化成百分比(不包含百分号)
     * 2位小数
     * @param num
     * @return
     */
    public static String percentStr(Double num) {
        if (num != null) {
            return String.format("%.2f", num*100);
        }else {
            return "-";
        }
    }

    /**
     * 转成字符串，并保留5位小数
     * @param num
     * @return
     */
    public static String double5ToStr(Double num){
        if (num != null){
            return String.format("%.5f", num);
        }else{
            return "";
        }
    }

    /**
     * 转成字符串，并保留2位小数
     * @param num
     * @return
     */
    public static String double2ToStr(Double num){
        if (num != null){
            return String.format("%.2f", num);
        }else{
            return "";
        }
    }

    /**
     * double去掉末尾.0
     * @param num
     * @return
     */
    public static String formatRemoveZero(Double num){
        DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
        return decimalFormat.format(num);
    }

}
